BASICS OF FUNCTIONS IN JAVASCRIPT
This note explains functions in simple language.
A function is one of the most important parts of JavaScript.
You will use functions in:
- front-end code
- backend code
- React
- Node.js
- form handling
- API requests
- reusable logic
So it is very important to understand this topic well.
1. What is a function?
A function is a separate block of code that performs a specific task.
You can imagine a function like a machine:
- it receives some data
- it works with that data
- it gives a result back
A function helps you avoid repeating the same code many times.
Diagram 1. A function as a machine
1. Input goes in
↓
2. Function does some work
↓
3. Output comes out
Explanation
This is the basic idea of a function.
Example:
- input:
2, 3, 5 - function: multiply numbers
- output:
30
Not every function must return a result, but many do.
2. Why functions are useful
Functions are useful because they help you:
- reuse code
- organize code
- make code easier to read
- split a big task into smaller parts
Without functions, you may need to write the same code again and again.
With functions, you write the logic once and use it many times.
Diagram 2. Without functions vs with functions
Without functions:
write code → copy it → copy it again → code becomes long
With functions:
write function once → call it many times → code stays clean
Explanation
Functions save time and make your program easier to maintain.
If you need to change the logic later, you change it in one place instead of many places.
3. Declaring a function
To create a function, you declare it.
A function declaration has these main parts:
- the keyword
function - the function name
- parentheses
() - curly braces
{}with the function body inside
Example
function doStuff() {
console.log("Log inside function");
}
Diagram 3. Parts of a function declaration
function doStuff() {
console.log("Log inside function");
}
1. function → tells JavaScript this is a function
2. doStuff → function name
3. () → place for parameters
4. { } → function body
Explanation
This function already exists after declaration, but it does not run automatically.
It will run only when it is called.
4. Function name
A function name should usually describe the action.
In JavaScript, function names are often verbs, because functions usually do something.
Good examples
function showMessage() {}
function calculateTotal() {}
function getUserName() {}
function createOrder() {}
These names answer the question:
- What does the function do?
Diagram 4. Good function naming
Bad names:
data()
test()
aaa()
Better names:
showMessage()
calculateTotal()
getUserName()
Explanation
A good name makes the code easier to understand.
When another developer reads calculateTotal(), they immediately understand the function's purpose better than with aaa().
5. Function body
The function body is the code inside curly braces {}.
This is the code that runs when the function is called.
Example
function doStuff() {
console.log("Function started");
console.log("Function finished");
}
The function body may contain:
- variables
- calculations
console.log()- conditions
- loops
- other functions
return
Diagram 5. What can be inside a function body
Function body
│
├─ variables
├─ calculations
├─ console.log()
├─ conditions
├─ loops
└─ return
Explanation
The function body is just normal JavaScript code, but it belongs to that function only.
6. Calling a function
Declaring a function does not execute it.
To execute it, you must call it.
A function call is written using:
- the function name
- parentheses
()
Example
function doStuff() {
console.log("Log inside function");
}
doStuff();
doStuff();
doStuff();
Output
Log inside function
Log inside function
Log inside function
Diagram 6. Declaring and calling
1. Declare the function
function doStuff() { ... }
2. Call the function
doStuff();
3. JavaScript runs the code inside the function
Explanation
A function can be called many times.
Every call runs the code again.
7. Read this code example
function greetClient() {}
What is it?
It is a function declaration.
- function name:
greetClient - parameters: none
- body: empty
This function exists, but it does nothing yet.
Diagram 7. Empty function
function greetClient() {}
1. The function exists
2. It has a name
3. It has no parameters
4. It has no code inside
5. Calling it does nothing
Explanation
An empty function is still a real function.
It just has no instructions inside.
8. Parameters
Parameters are values written inside the parentheses when the function is declared.
They are like placeholders.
Example
function multiply(x, y, z) {
console.log(`Result: ${x * y * z}`);
}
Here:
xyz
are parameters.
Diagram 8. Parameters in a function declaration
function multiply(x, y, z) { ... }
1. x → first parameter
2. y → second parameter
3. z → third parameter
Explanation
Parameters are local variables that exist only inside the function.
They receive values when the function is called.
9. Arguments
Arguments are the real values passed to the function during the call.
Example
function multiply(x, y, z) {
console.log(`Result: ${x * y * z}`);
}
multiply(2, 3, 5);
Here:
- parameters:
x,y,z - arguments:
2,3,5
During this call:
x = 2y = 3z = 5
Diagram 9. Parameters vs arguments
Function declaration:
function multiply(x, y, z)
Parameters:
x, y, z
Function call:
multiply(2, 3, 5)
Arguments:
2, 3, 5
Explanation
Parameters belong to the function declaration.
Arguments belong to the function call.
This is a very important difference.
10. Order of arguments matters
Arguments are matched to parameters by order.
- first argument → first parameter
- second argument → second parameter
- third argument → third parameter
Example
function showValues(a, b, c) {
console.log(a, b, c);
}
showValues("red", "green", "blue");
Diagram 10. How arguments are matched
showValues("red", "green", "blue")
a = "red"
b = "green"
c = "blue"
Explanation
JavaScript matches values by position, not by name.
If you change the order of arguments, the function receives different values.
11. One function can be used many times
function multiply(x, y, z) {
console.log(`Result: ${x * y * z}`);
}
multiply(2, 3, 5); // Result: 30
multiply(4, 8, 12); // Result: 384
multiply(17, 6, 25); // Result: 2550
The same function works with different arguments.
Diagram 11. Reusing one function
multiply(2, 3, 5) → 30
multiply(4, 8, 12) → 384
multiply(17, 6, 25) → 2550
Explanation
This is one of the biggest advantages of functions.
You write the logic once, then reuse it with different data.
12. Parameters are local
Parameters only exist inside the function where they are declared.
Example
function greet(name) {
console.log(name);
}
The variable name exists only inside greet().
Diagram 12. Parameter scope
function greet(name) {
console.log(name);
}
Inside greet():
name exists
Outside greet():
name does not exist
Explanation
Parameters are local to the function, just like local variables.
13. Read this code example
function calculate(x, y) {}
calculate(5, 8);
What happens here?
- function name:
calculate - parameters:
x,y - arguments:
5,8
So during this call:
x = 5y = 8
Diagram 13. Matching in this example
calculate(5, 8)
x = 5
y = 8
Explanation
This function body is empty, so nothing happens, but the argument matching still exists.
14. Returning a value
The return keyword sends a value back from a function.
When JavaScript sees return, it:
- stops the function immediately
- sends the value back to the place where the function was called
Example
function multiply(x, y, z) {
return x * y * z;
}
const result = multiply(2, 3, 5);
console.log(result); // 30
Diagram 14. How return works
1. Function gets values
2. Function calculates result
3. return sends result back
4. The calling code receives it
Explanation
Here:
- input:
2, 3, 5 - calculation:
2 * 3 * 5 - returned value:
30
That returned value is stored in result.
15. Returning with an extra variable
You can first save a result into a variable and then return it.
Example
function multiply(x, y, z) {
const product = x * y * z;
return product;
}
This is correct and often easy to read.
Diagram 15. Return through a variable
x * y * z
↓
save result in product
↓
return product
Explanation
This style is useful when the logic is a little longer and you want cleaner code.
16. Returning directly
If the expression is simple, you can return it directly.
Example
function multiply(x, y, z) {
return x * y * z;
}
Diagram 16. Direct return
return x * y * z;
Explanation
This is shorter than creating a separate variable.
Both versions are correct.
17. If there is no return
If a function has no return, JavaScript automatically returns:
undefined
Example
function multiply(x, y, z) {
const product = x * y * z;
}
const result = multiply(2, 3, 5);
console.log(result); // undefined
Diagram 17. Function without return
Function runs
↓
No return found
↓
JavaScript gives back undefined
Explanation
This is very important:
console.log()prints somethingreturnsends a value back
They are not the same.
18. console.log() and return are different
Example 1: only logging
function makeMessage(username) {
console.log(`Hello ${username}`);
}
makeMessage("Jacob");
This prints:
Hello Jacob
But the function still returns undefined.
Example 2: returning
function makeMessage(username) {
return `Hello ${username}`;
}
const message = makeMessage("Jacob");
console.log(message);
Now the function returns the string.
Diagram 18. console.log() vs return
console.log()
→ shows data in console
return
→ sends data back from function
Explanation
Many beginners confuse these two ideas.
They are very different.
19. Code after return does not run
When JavaScript reaches return, the function ends immediately.
Example
function multiply(x, y, z) {
console.log("This runs");
return x * y * z;
console.log("This never runs");
}
Diagram 19. return stops the function
Function starts
↓
Code before return runs
↓
return is reached
↓
Function ends
↓
Code after return is skipped
Explanation
Everything after return in the same function becomes unreachable.
20. Read this code example
function makeMessage(username) {
console.log(`Hello ${username}`);
}
makeMessage("Jacob");
What happens?
- parameter:
username - argument:
"Jacob" - output in console:
Hello Jacob
But since there is no return, the function result is still:
undefined
Diagram 20. What happens in makeMessage("Jacob")
1. username receives "Jacob"
2. console.log() prints Hello Jacob
3. no return is found
4. function returns undefined
Explanation
The message appears in the console, but it is not returned.
21. Order of code execution
JavaScript runs code from top to bottom.
When it sees a function call, it pauses the current place and goes into the function.
After the function ends, JavaScript returns to the place where the function was called.
Example
function multiply(x, y, z) {
console.log(`Result: ${x * y * z}`);
}
console.log("Log before multiply execution");
multiply(2, 3, 5);
console.log("Log after multiply execution");
Diagram 21. Order of execution
1. "Log before multiply execution"
2. call multiply(2, 3, 5)
3. run function body
4. "Result: 30"
5. return to main code
6. "Log after multiply execution"
Explanation
JavaScript temporarily leaves the main flow, executes the function, then comes back.
22. Read this code fragment
console.log("A");
function logStuff() {
console.log("B");
}
console.log("C");
logStuff();
console.log("D");
Output
A
C
B
D
Diagram 22. Why the output is A, C, B, D
1. console.log("A") runs
2. function logStuff is declared
3. console.log("C") runs
4. logStuff() is called
5. console.log("B") runs inside the function
6. console.log("D") runs
Explanation
Function declaration does not print anything by itself.
Only the function call runs the code inside.
23. What is scope?
Scope means the area of code where a variable or function can be used.
Scope answers this question:
Where is this variable visible?
This is very important in JavaScript.
Diagram 23. What scope means
Scope = visibility area of a variable or function
Explanation
Some variables can be used almost everywhere.
Some variables can only be used inside a specific block.
24. Global scope
A variable declared outside all functions and blocks is in the global scope.
Such a variable is called a global variable.
Example
const value = "I'm a global variable";
function foo() {
console.log(value);
}
foo();
console.log(value);
Diagram 24. Global scope
Global scope
│
├─ const value = "I'm a global variable"
│
├─ function foo() can use value
└─ code outside foo() can also use value
Explanation
Because value is global, it is visible in many places after declaration.
25. Local scope
A block with curly braces {} creates a local scope.
Examples:
- functions
- loops
- conditions
A variable declared inside such a block is called a local variable.
Example
function foo() {
const value = "I'm a local variable";
console.log(value);
}
foo();
console.log(value); // Error
Diagram 25. Local scope inside a function
function foo() {
const value = "I'm a local variable";
}
Inside foo():
value exists
Outside foo():
value does not exist
Explanation
The variable value belongs only to the function body.
Outside the function, JavaScript cannot see it.
26. Why the error happens
This line:
console.log(value);
outside the function causes an error.
Typical error:
ReferenceError: value is not defined
Diagram 26. Why local variable access fails
1. value is created inside foo()
2. foo() ends
3. outside code tries to access value
4. JavaScript cannot find it
5. error happens
Explanation
A local variable cannot be used outside its scope.
27. Global vs local variables together
const globalValue = "Global";
function test() {
const localValue = "Local";
console.log(globalValue); // Global
console.log(localValue); // Local
}
test();
console.log(globalValue); // Global
console.log(localValue); // Error
Diagram 27. Global and local visibility
Global variable:
visible inside and outside function
Local variable:
visible only inside function
Explanation
A function can use global variables.
But code outside the function cannot use local variables from inside that function.
28. Simple function without parameters
function sayHello() {
console.log("Hello!");
}
sayHello();
Diagram 28. Function without parameters
sayHello()
↓
runs function body
↓
prints "Hello!"
Explanation
This function does not need input values.
It always does the same thing.
29. Function with one parameter
function greetUser(name) {
console.log(`Hello, ${name}!`);
}
greetUser("Nikita");
greetUser("Sarah");
Diagram 29. Same function, different arguments
greetUser("Nikita") → Hello, Nikita!
greetUser("Sarah") → Hello, Sarah!
Explanation
The function logic stays the same, but the argument changes the result.
30. Function that returns a value
function add(a, b) {
return a + b;
}
const result = add(5, 7);
console.log(result); // 12
Diagram 30. Function returning a result
add(5, 7)
↓
5 + 7
↓
return 12
↓
result = 12
Explanation
This is one of the most common patterns in programming.
31. Function reused many times
function square(number) {
return number * number;
}
console.log(square(2)); // 4
console.log(square(3)); // 9
console.log(square(4)); // 16
Diagram 31. Reuse with different values
square(2) → 4
square(3) → 9
square(4) → 16
Explanation
A function is reusable logic.
You do not need to rewrite the same formula each time.
32. Function with no return
function showMessage(text) {
console.log(text);
}
const result = showMessage("Hi");
console.log(result); // undefined
Diagram 32. Logging but not returning
showMessage("Hi")
↓
prints "Hi"
↓
no return found
↓
result = undefined
Explanation
The function prints the text, but it does not send a value back.
33. Common beginner mistakes
Mistake 1. Forgetting to call the function
function sayHi() {
console.log("Hi");
}
This only declares the function.
To run it, you need:
sayHi();
Diagram 33. Declaration is not execution
function sayHi() { ... } → function is created
sayHi(); → function is executed
Explanation
Many beginners think the function runs when it is declared.
It does not.
Mistake 2. Mixing up parameters and arguments
function greet(name) {}
greet("Aaron");
nameis a parameter"Aaron"is an argument
Diagram 34. Parameter vs argument again
Declaration side → parameter
Call side → argument
Explanation
This difference is small, but important.
Mistake 3. Thinking console.log() is the same as return
They are not the same.
Diagram 35. Very important difference
console.log()
→ display
return
→ send back
Explanation
A function can print something and still return undefined.
Mistake 4. Writing code after return
function getNumber() {
return 5;
console.log("This will not run");
}
Diagram 36. After return = unreachable
return 5;
↓
function ends here
↓
next line is ignored
Explanation
Once return happens, the function stops.
Mistake 5. Using a local variable outside its function
function test() {
const age = 25;
}
console.log(age); // Error
Diagram 37. Local variable mistake
Inside function:
age exists
Outside function:
age does not exist
Explanation
A local variable stays inside its own scope.
34. Full summary
A function is a reusable block of code that does a specific task.
A function is declared with:
function- a name
- parentheses
- curly braces
A function runs only when it is called.
A parameter is a variable in the function declaration.
An argument is a real value passed during the function call.
The return keyword:
- sends a value back
- stops the function immediately
If there is no return, the function returns undefined.
Global scope means a variable is declared outside functions and blocks.
Local scope means a variable is declared inside a block and works only there.
Diagram 38. Final function map
Function basics
│
├─ Declaration
├─ Call
├─ Parameters
├─ Arguments
├─ Return
├─ Execution order
└─ Scope
├─ Global
└─ Local
Explanation
These are the core ideas you must understand before moving to more advanced function topics.
35. Quick revision block
1. A function is a reusable block of code
2. A function is declared with the function keyword
3. A function runs only when it is called
4. Parameters are written in the declaration
5. Arguments are written in the call
6. Arguments are matched by order
7. return sends a value back
8. Code after return does not run
9. Without return, the function gives undefined
10. Global variables are visible in many places
11. Local variables work only inside their own block
36. Final conclusion
Functions are one of the foundations of JavaScript.
If you understand:
- how to declare a function
- how to call it
- what parameters and arguments are
- how
returnworks - how code execution order works
- what scope means
then you already have a strong base for real programming.
Functions are used everywhere in full stack development:
- in UI logic
- in event handling
- in React components
- in backend routes
- in helpers and utilities
- in API logic
Send the next topic, and I'll rewrite it in the same style with more numbered diagrams again.